#!/usr/bin/perl
#
# Find people who have been frozen, and should not have been.
#
#

use Counter;
use POSIX qw(strftime);
use DBI;
use Getopt::Long;
use HTTP::Date;


$count = 100;

GetOptions("test" => \$test,
	   "count=i" => \$count,
	   "debug" => \$DEBUG,
	   );


$users = Counter::open(O_RDWR);

$dbh = $FileTable::dbhandle;

# get all the userupdate events for the last 2 years
$sth = $dbh->prepare("SELECT uniqueid, reckey, operation, data, date
	FROM f_log WHERE date > '1999-10-01' AND tablename = 'persons'
	AND data like '%ident:script=cgi-bin/userupdate.cgi%'
	LIMIT $count");
$sth->execute() || die "Unable to find the log entries\n";

while ($rec = $sth->fetchrow_hashref) {
    if ($$rec{data} =~ /user=\n/) {
	$DEBUG && warn "$$rec{reckey} $$rec{uniqueid}:  User self update\n";
	if ($$rec{data} =~ /recdate:(.+)\n/) {
	    $recdate = $1;
	    if ($ztime = str2time($recdate)) {
		$recdate = strftime("%Y-%m-%d %H:%M:%S", gmtime($ztime));
		$user = $users->get($$rec{reckey});
		if ($user) {
		    if ($user->{logintime} lt $recdate) {
			warn "$$rec{reckey}: move logintime from ",
			$user->{logintime}, " to $recdate\n";
			if ($user->{state} eq "frozen") {
			    if ($recdate lt '1999-11-01') {
				warn "$$rec{reckey}: Patching but not thawing\n";
				++ $results{changenothaw};
			    } else {
				warn "$$rec{reckey}: Thawing record\n";
				++ $results{thaw};
				$user->thaw() if !$test;
			    }
			} else {
			    ++ $results{changelogin};
			}
			# there is a perverted MySQL thing here...
			# using the non-compact syntax fails the SQL,
			# even though the same syntax works elsewhere
			# in the same statement, even!
			$recdate2 = strftime("%Y%m%d%H%M%S", gmtime($ztime));
			#warn "Setting logintime to $recdate2\n";
			$user->{logintime} = $recdate2;
			$user->patch() if !$test;
		    } else {
			++ $results{nochange};
		    }
		} else {
		    warn "$$rec{reckey}: No user entry\n";
		    ++ $results{missinguser};
		}
	    } else {
		warn "$$rec{reckey}: Unable to parse $recdate\n";
		++ $results{noparserecdate};
	    }
	} else {
	    ++ $results{norecdate};
	}
    } elsif ($$rec{data} =~ /user=\S+\n/) {
	$DEBUG && warn "$$rec{reckey} $$rec{uniqueid}:  User admin update\n";
	++ $results{adminupdate};
    }
}
for $result (sort(keys(%results))) {
    print $results{$result}, " ", $result, "\n";
    $sum += $results{$result};
}
print "Total is $sum\n";
